<?
class Email_model extends CI_Model
{
	public $from_name = 'Робот simpleblog';
	public $from_email = 'sblog@coddism.com';
	
	function __construct()
	{
		parent::__construct();
		$this->load->library('email');
	}

	function checkLimits()
	{
		if (!$this->settings->data->mailSentLimited || !$this->settings->data->mailSentCount || !$this->settings->data->mailSentPeriod)
			return true;
		
		$count = $this->db->where('dSending >', now() - $this->settings->data->mailSentPeriod)->count_all_results('mail_sent');
		return ($count < $this->settings->data->mailSentCount);
	}

	function valid_email($address)
	{
		return $this->email->valid_email($address);
	}
	
	function sendEmail($recipient, $subject = 'Test email', $message = 'Hello World', $log = true)
	{
		$res = $this->checkLimits();
		// echobr('checkLimits - '.var_export($res, true));

		if ($res)
		{
			$this->email->from($this->from_email, $this->from_name);
			$this->email->to($recipient); 
			$this->email->subject($subject);
			$this->email->message($message);
			$result = $this->email->send();

			// echobr('email->send - '.var_export($result, true));
			// Для статистики и подсчета писем для проверки ограничений
			if ($log)
				$this->db->insert('mail_sent',
					array(
						'tMailing' => 0,
						'pSenderType' => 0,
						'tSender' => 0,
						'dSending' => now(),
						'pStatus' => (int)$result,
					));

			$this->sendQueue();

			return $result;
		}
		else
		{
			// echobr('log = '.$log);
			if ($log === 2)
				return false;

			// echobr('insert mail_queue');
			return $this->db->insert('mail_queue',
				array(
					'pEmail' => $recipient,
					'pTitle' => $subject,
					'pText' => $message,
					'dCreated' => 0,
				));
		}

	}

	function sendQueue()
	{
		$result = $this->db->get('mail_queue', 1)->row();

		// echobr('mail_queue empty - '.var_export(empty($result), true));
		if (empty($result))
			return false;
		
		if ($send =  $this->sendEmail($result->pEmail, $result->pTitle, $result->pText, 2))
			$this->db->where('id', $result->id)->delete('mail_queue');
		return $send;
	}
	
	function sendTemplateEmail($recipient, $template, $data)
	{
		$temp = $this->db->select('pTitle, pText')->where('pKey', $template)->get('mail_template')->row();
		
		if (!$temp)
			return false;

		foreach ($data as $key=>$val)
		{
			$temp->pText = str_replace('*'.$key.'*', $val, $temp->pText);
			$temp->pTitle = preg_replace('*'.$key.'*', $val, $temp->pTitle);
		}

		return $this->sendEmail($recipient, $temp->pTitle, $temp->pText);
	}
}
?>